package archivemanagement;

import static com.google.common.base.Throwables.propagate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.UUID;

import metagrammar.Operator;
import metagrammar.Type;

import com.google.inject.Inject;

public class TypeManager implements ArchiveManager<UUID, Type> {
    
    private final Collection<TypeArchive> libraries;
    
    @Inject
    public TypeManager(TypeArchive... typeLibraries)
    {
        libraries = new ArrayList<TypeArchive>(Arrays.asList(typeLibraries));
    }
    
    @Override
    public Type load(UUID key)
    {
        for(TypeArchive lib : libraries) {
            Type type;
            try {
                type = lib.loadType(key);
                if(type != null) {
                    return type;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return null;
    }
    
    @Override
    public void add(Type value)
    {
        for(TypeArchive lib : libraries) {
            try {
                lib.writeType(value);
            }
            catch(IOException e) {
                propagate(e);
            }
        }
    }
    
    @Override
    public int update(Type value)
    {
        int updatedLibraries = 0;
        for(TypeArchive lib : libraries) {
            try {
                if(lib.containsType(value.getId())) {
                    lib.writeType(value);
                    updatedLibraries++;
                }
            }
            catch(IOException e) {
                propagate(e);
            }
        }
        return updatedLibraries;
    }
    
    @Override
    public Collection<Type> loadAll()
    {
        ArrayList<Type> types = new ArrayList<Type>();
        for(TypeArchive lib : libraries) {
            try {
                types.addAll(lib.loadAllTypes());
            }
            catch(IOException e) {
                throw propagate(e);
            }
        }
        return types;
    }
    
    public int update(Operator value)
    {
        return 0;
    }
    
}